<template>
	<div class="bg">
		<goback :title="`${user.name}`"></goback> <!-- 假设goback是一个返回按钮组件 -->
		
		
		<div class="content" ref="content">
			
			<div :class="message.sender==='Me'?'chat-message-me':'chat-message-other'"
				:style="{'padding-bottom':messages.length-1===index?'2rem':'none'}"
				v-for="(message, index) in message_content.messages" :key="index">
			
				<!--            消息头像-->
				<div :class="message.sender==='Me'?'message-me-asWhole-headPortrait':'message-other-asWhole-headPortrait'">
					<img v-if="message.sender=='Me'" @click="goMineCard" :src="getMyHead()" class="examineeFace_logo_style">
					<img v-else @click="goOtherCard" :src="getOtherHead()" class="examineeFace_logo_style">
				</div>
			
			
				<!--          消息-->
				<div :class="message.sender==='Me'?'message-me-asWhole-right':'message-other-asWhole-right'">
					<!--            消息上面-->
					<div :class="message.sender==='Me'?'message-me-asWhole-top':'message-other-asWhole-top'"
						v-if="message.sender=='Me'">
						我
					</div>
					<div :class="message.sender!=='Me'?'message-me-asWhole-top':'message-other-asWhole-top'" v-else>
						{{message_content.uid.name}}
					</div>
			
			
					<!--          消息内容-->
					<div
						:class="[message.sender==='Me'?'message-me':'message-other',message.isThinking===true?'message-animation':'']">
						{{message.content}}
					</div>
				</div>
				
			
			
			
			</div>
			
		</div>

		
		<div class="placeblock">
			
		</div>

		
		<div class="msgsend_box">
			<recoderModal @result="getVoice"></recoderModal>
			<input ref="inputField" @blur="handleBlur" v-model="now_message" class="msgsend_box_input"
				placeholder="请输入内容..."></input>
			<MyEmojis @select="onEmojiSelect" />
			<button @click="addmsg(now_message)">发送</button>
		</div>
	</div>
</template>

<script>
	export default {
		name: "message",

		data() {
			return {
				user:{},
				page_uid: 0,
				now_message: '',
				message_content: {
					uid: {
						name: ''
					},
					messages: []
				},
				messages: [],
				caretPosition: {
					start: 0,
					end: 0
				},
				watcher: null,
				


			};
		},
		mounted() {
			this.page_uid = this.$route.query.uid;;
			this.getUser();
			this.getData();
		},

		computed:{

		},
		methods: {
			getUser(){
				this.axios.get(`${this.IP}/getUserByUID`, {
					params: {
						uid: this.$route.query.uid
					}
				}).then(res => {
					this.user = res.data;
				})
			},
			getData() {
			
				this.axios.get(`${this.IP}/get_relate_with_me`, {
					params: {
						token: this.getStorage("token"),
					}
				}).then(res => {
					this.messages = res.data;
					this.$store.commit('setMessages', this.messages);
					
					
					this.messages = this.$store.getters.getMessages;
					this.messages.forEach((e) => {
						if (e.uid.uid == this.page_uid) {
							this.message_content = e;
						}
					})
					
					this.sortedMessagesComputed();
					this.scrollBottom();
					
				}).catch(error => {
					// 处理错误  
					console.error('请求出错：', error);
				});;
			},
			scrollBottom(){
				this.$nextTick(() => {
				let scrollElem = this.$refs.content;
				
				scrollElem.scrollTo({ top: scrollElem.scrollHeight, behavior: 'smooth' });
				})
			},

			sortedMessagesComputed() {
			      // 在这里进行排序，并确保只在message_content.messages发生变化时重新排序  
			      return this.message_content.messages.sort((a, b) => a.timestamp - b.timestamp);  
			},
			getMyHead() {
				return `${this.IP}/img/${this.$store.getters.getUser.uid}.jpg`;
			},
			getOtherHead() {
				return `${this.IP}/img/${this.page_uid}.jpg`;
			},
			goMineCard() {
				this.$router.push(`/userInfo?uid=${this.$store.getters.getUser.uid}`);
			},
			goOtherCard() {
				this.$router.push(`/userInfo?uid=${this.page_uid}`);
			},
			handleBlur() {
				this.caretPosition = {
					start: this.$refs.inputField.selectionStart,
					end: this.$refs.inputField.selectionEnd,
				};

			},
			onEmojiSelect(emoji) {
				// 当Emoji被选中时，将其添加到message中  
				this.now_message = this.now_message.slice(0, this.caretPosition.start) + emoji + this.now_message.slice(
					this.caretPosition.start, this.now_message.length)
			},
			getVoice(e) {
				this.now_message=e;
			},
			addmsg(e) {
				
				let me = {
					isRead: 'SENT',
					content: e,
					sender: 'Me',
					timestamp: new Date().getTime()
				}
				
				

				
				
				
				this.message_content.messages.push(me);
				this.now_message = '';
				const send_msg = JSON.stringify({
					action: 'send_to_other',
					data: {
						content: e,
						who_uid: this.page_uid
					}
				});
				this.$store.getters.getSocket.send(send_msg);
				

				
				this.axios.get(`${this.IP}/send_msg`, {
					params: {
						token: this.getStorage("token"),
						content: e,
						uid: this.page_uid
					}
				}).then(res => {
					this.messages = res.data;
				}).catch(error => {
					// 处理错误  
					console.error('请求出错：', error);
				});;
				
				
				this.scrollBottom();
				
				
				
				
				
				
			},


			toggle() {
				this.voice_type = !this.voice_type;
			},


		}
	};
</script>

<style scoped>
	.animation{
		animation: 3s swing alternate-reverse ease;
	}
	.bg{
		overflow: hidden;
		min-height: 100vh !important;
		height: auto;
	}
	.content{
		overflow-y: scroll;
		display: flex;
		flex-direction: column;
		height: auto;
		
	}
	.chat-message-other {
		/*background-color: red;*/
		display: flex;
		padding-left: 1vw;
		padding-top: 1vw;
		align-self: flex-start;
	}

	.chat-message-me {
		/*background-color: red;*/
		display: flex;
		padding-right: 1vw;
		padding-top: 1vw;
		flex-direction: row-reverse;
		/* 将子div的顺序反转 */
		align-self: flex-end;
	}

	.message-me-asWhole-headPortrait {
		padding: 3px;
	}

	.message-other-asWhole-headPortrait {
		padding: 3px;
	}

	.message-me-asWhole-right {
		display: flex;
		flex-direction: column;
		/* 设置子元素垂直排列 */
		margin-left: 0.1rem;
	}

	.message-other-asWhole-right {
		display: flex;
		flex-direction: column;
		/* 设置子元素垂直排列 */
		margin-left: 0.1rem;
	}

	.message-me-asWhole-top {
		padding: 1vw;
		/* font-size: 12px; */
		font-family: 微软雅黑;
		padding: 3px;
		color: rgba(134, 144, 156, 1);
		text-align: right;
	}

	.message-other-asWhole-top {
		padding: 3px;
		/* font-size: 12px; */
		font-family: 微软雅黑;
		padding: 3px;
		color: rgba(134, 144, 156, 1);
	}

	.message-me {
		background-color: #fff;
		max-width: 280px;
		word-wrap: break-word;
		/* 处理英文单词换行 */
		word-break: break-all;
		/* 处理中文换行 */
		display: inline-block;
		/*将div元素转换为行内块元素*/
		width: auto;
		/* 宽度根据文本宽度自动调正*/
		padding: 6px 12px;
		border-radius: 4px;
		font-size: 26px;
	}

	.message-other {
		background-color: #fff;
		max-width: 280px;
		word-wrap: break-word;
		/* 处理英文单词换行 */
		word-break: break-all;
		/* 处理中文换行 */
		display: inline-block;
		/*将div元素转换为行内块元素*/
		width: auto;
		/* 宽度根据文本宽度自动调正*/
		padding: 6px 12px;
		border-radius: 4px;
		font-size: 26px;
	}


	.examineeFace_logo_style {
		width: 64px;
	}

	.msgsend_box {
		position: fixed;
		bottom: 0px;
		width: 100vw;
		background-color: #ebebeb;
		border-top: 1px solid #efefef;
		padding: 1vw;
		display: flex;
		box-sizing: border-box;
		align-items: center;
	}

	.msgsend_box img {
		width: 64px;
	}

	.msgsend_box_input {
		flex: 1;
		height: 5vw;
		border-radius: 20px;
		padding: 2vw;
		margin: 1vw;
	}

	.msgsend_box_voice {
		flex: 1;
		height: 5vw;
		border-radius: 10px;
		padding: 2vw;
		margin: 1vw;
		background-color: #fff;
		border-radius: 20px;
	}

	.msgsend_box button {
		width: 10vw;
		height: 9vw;
	}




	.message-animation {
		/* 添加你想要的样式，例如闪烁效果或简单的文本显示 */
		animation: blinker 1s linear infinite;
	}

	@keyframes blinker {
		50% {
			opacity: 0;
		}
	}
</style>